<template>
    <el-form :model="form" ref="formRef">
        <el-form-item label="用户名" prop="username" :rules="[{required:true,message: '请输入用户名'}]">
            <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" :rules="[{required:true,message: '请输入密码'}]">
            <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="角色:" prop="role" :rules="[{required:true,message: '请选择角色'}]">
            <el-radio-group v-model="form.role">
                <el-radio value="teacher">教师</el-radio>
                <el-radio value="student">学生</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">登录</el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import {ref} from 'vue';
import {useRouter} from 'vue-router'
import {useUserStore} from '../stores/user'
import {useStudentStore} from '../stores/student'
import {ElMessage} from 'element-plus'

const form = ref({
    username:'',
    password:'',
    role:''
})
const formRef = ref(null)

const router = useRouter()
const useStore = useUserStore()
const studentStore = useStudentStore()

const onSubmit = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            if (form.value.role === 'student') {
                const student = studentStore.getStudentByUsername(form.value.username)
                if (student && student.password === form.value.password) {
                    user.login(student)
                    router.push('/profile')
                } else {
                    ElMessage.error('用户名或密码错误')
                    form.value.username = ''
                    form.value.password = ''
                    form.value.role = '' 
                }
            } else if (form.value.role === 'teacher') {
                if (form.value.username === 'teacher' && form.value.password === '123456') {
                    useStore.login({username: 'teacher' ,role: 'teacher'})
                    router.push('/students')
                } else {
                    ElMessage.error('用户名或密码错误')
                    form.value.username = ''
                    form.value.password = ''
                }
            }
        }
    })
}

const cancel = () => {
    router.push('/')
}
</script>